package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 全局过滤
     *
     * @param exchange
     * @param chain
     * @return
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断是否是登录功能,是登录功能,直接放行
        if (request.getURI().getPath().contains("/login/in")) {
            return chain.filter(exchange);
        }
        //3接收token,判断是否为空
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        // System.out.println("headers = " + headers);

        //4 如果为空,返回前端401(权限不够) 错误
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //5. 如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i == -1 || i == 0) {
                //token有效,获取用户id
                Integer id = (Integer) claims.get("id");
                log.info("find userid:{} from uri:{}", id, request.getURI());
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders ->
                        httpHeaders.add("userId", id + "")
                ).build();
                System.out.println("headers = " + headers);
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //想客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6. 放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器,优先级设置,数字越小,优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

 /* @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断是否是登录功能,是登录功能,直接放行
        if (request.getURI().getPath().contains("/login/in")) {
            return chain.filter(exchange);
        }
        //3 接收token,判断是否为空
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        //4 如果为空,返回前端401(权限不够) 错误
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        }
        //2.从cookie中获取jti的值,如果该值不存在,拒绝本次访问
        HttpCookie uid = request.getCookies().getFirst("uid");
        String name =null;
        if (uid!=null){
             name = uid.getValue();
        }
        if (uid==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3.根据uid 在redis中获取值
        String token = this.redisTemplate.opsForValue().get(name);

        if (StringUtils.isEmpty(token)){
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //5. 如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i == -1 || i == 0) {
                //token有效,获取用户id
                Integer id = (Integer) claims.get("id");
                log.info("find userid:{} from uri:{}",id,request.getURI());
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders ->
                        httpHeaders.add("userId", id + "")
                ).build();

                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //想客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6. 放行
        return chain.filter(exchange);
    }
*/
    /**
     * 过滤器,优先级设置,数字越小,优先级越高
     *
     * @return
     */
/*    @Override
    public int getOrder() {
        return 0;
    }*/
}
